#include "combofield.h"
#include <qplugin.h>
#include <QComboBox>
#include <QSqlQuery>
#include <QDebug>

ComboField::ComboField()
{
}

QWidget *ComboField::createDelegate(const QVariantMap &properties)
{
    QComboBox *combo = new QComboBox();
    combo->setEditable(false);

    if (properties.contains("table")) {
        QString table = properties["table"].toString();
        QString nameField = properties["name_field"].toString();

        QSqlQuery sql;
        sql.exec(QString("SELECT `id`,`%1` FROM `%2` WHERE 1;").arg(nameField).arg(table));

        int i = 0;
        while (sql.next()) {
            QVariant id = sql.value(0);
            QString name = sql.value(1).toString();

            combo->insertItem(i++, name, id);
        }
    }

    return combo;
}

void ComboField::setEditable(QWidget *delegate, bool editable)
{
    QComboBox *edit = (QComboBox *)delegate;
    edit->setEnabled(editable);
}

QVariant ComboField::data(QWidget *delegate) const
{
    QComboBox *edit = (QComboBox *)delegate;

    QVariant userRole = edit->itemData(edit->currentIndex(), Qt::UserRole);

    return userRole;
}

void ComboField::setData(QWidget *delegate, const QVariant &data)
{
    QComboBox *edit = (QComboBox *)delegate;

    int idx = edit->findData(data, Qt::UserRole, Qt::MatchExactly);
    edit->setCurrentIndex(idx);
}

void ComboField::clear(QWidget *delegate)
{
    QComboBox *edit = (QComboBox *)delegate;
    edit->setCurrentIndex(0);
}

Q_EXPORT_PLUGIN2(combo-field, ComboField)
